//
//  GameKitManager.m
//  MessangerSkeleton
//
//  Created by User-23 on 4/26/14.
//  Copyright (c) 2014 IOTrainingCamp. All rights reserved.
//

#import "GameKitManager.h"

#import "GamePlay.h"


@interface GameKitManager()

//@property(nonatomic) NSString *timeStartLookingForOpponent;

@property(nonatomic) GamePlay *gamePlay;

@end


@implementation GameKitManager

@synthesize gkPeerID;
@synthesize gkSession;


static BOOL isInited;

#pragma mark - init a Singleton object
+ (id)sharedInstance
{
    static GameKitManager *instance = nil;
    if ( !instance ) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[super alloc] init];
        });
    }
    return instance;
}

+ (id)alloc
{
    return [GameKitManager sharedInstance];
}

- (id)init
{
    if ( !isInited ){
        self = [super init];
        if ( self ) {
            self.gamePlay = [GamePlay sharedInstance];
        }
    }
	return self;
}


//cancel searching for an opponent
- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker
{
	picker.delegate = nil;
    self.gamePlay.gameState = kGameStateLaunchedMultiPlayer;
    
    [self endSession];
    
    //posting a notification
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkNotificationNameForCanceledLookingForAnOpponent object:nil];
    
    NSLog(@"GK - cancel looking an for opponent");
    
}

//connect with an opponent
- (void)peerPickerController:(GKPeerPickerController *)picker
              didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
    self.gkPeerID = peerID;
    self.gkSession = session;
    [gkSession setDataReceiveHandler:self withContext:NULL];
    gkSession.delegate = self;
	
    [picker dismiss];
    picker.delegate = nil;
    
    //posting a notification
    //the object is needed only in NetworkManager
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkNotificationNameForConnectedPeer object:nil];
    
    NSLog(@"GK - Connect to peerID = %@", peerID);
    
   // [self sendingStartingTimeToFindWhoIsFirst];
}

//receive data
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer
          inSession:(GKSession *)session context:(void *)context {
    
    NSLog(@"GK - Received some data");
    
    //posting a notification
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkManagerNotificationNameForReceivedData object:data];
    
}

- (void)session:(GKSession *)session peer:(NSString *)peerID
 didChangeState:(GKPeerConnectionState)state {
    
    if ( [gkPeerID isEqualToString:peerID] && state == GKPeerStateDisconnected ) {
        
//        [gkSession disconnectFromAllPeers];
//        gkSession.delegate = nil;
//        self.gkSession = nil;
//        self.gkPeerID = nil;
//        NSLog(@"disconnected");
        [self endSession];
        
        //posting a notification
        [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkManagerNotificationNameForDisconnecting object:nil];
    }
    //case GKPeerStateAvailable, GKPeerStateUnavailable, and GKPeerStateConnected
}

- (void)endSession
{
    if ( self.gkSession ) {
        [self.gkSession disconnectFromAllPeers];
        self.gkSession.delegate = nil;
        self.gkSession.available = NO;
        [self.gkSession setDataReceiveHandler: nil withContext: NULL];
        self.gkSession = nil;
        self.gkPeerID = nil;
        
        NSLog(@"GK - endSession");
    }
}


- (void)startLookingForOponent
{
//    self.timeStartLookingForOpponent = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterFullStyle];
//    
//    NSLog(@"self.startLookingForOpponent = %@", self.timeStartLookingForOpponent);
    
    GKPeerPickerController *picker;
    picker = [[GKPeerPickerController alloc] init];
    picker.delegate = self;
    
    [picker show];
}

//- (NSString *)timeStartLookingForOpponent
//{
//    return _timeStartLookingForOpponent;
//}

- (void)sendData:(NSData *)data
        withMode:(DataMode)dataMode
{
    NSError *error = nil;
    [gkSession sendDataToAllPeers:data withDataMode:[self getGKSendDataModeFromDataMode:dataMode] error:&error];
    if ( error ){
        NSLog(@"Error in sending data - %@", [error localizedDescription]);
    }
}

- (GKSendDataMode)getGKSendDataModeFromDataMode:(DataMode)dataMode
{
    if ( dataMode == reliable )
    {
        return  GKSendDataReliable;
    }
    return GKSendDataUnreliable;
}

@end
